function [vert_index, vert_flag, click_pt] = isvertex(h_fig, h_axes, h_line);

% ISVERTEX - determine whether a vertex on a line/rectangle was selected
%
%    [INDEX, FLAG, PT] = ISVERTEX(H_FIG, H_AXES, H_LINE) determines whether
%    the previous mouse click occurred within a specified distance of a
%    vertex on a line or rectangle object.  If a vertex is selected, FLAG = 1
%    and the vertex index is returned as INDEX.  If a segment is selected,
%    FLAG = 0 and INDEX is set to be N, where N and N + 1 are the indices
%    of the vertices comprising the segment endpoints.  The (X, Y) coordinates
%    of the click are returned as PT.
%
%    Note that rectangle coordinates are expanded from [X1 X2] and [Y1 Y2]
%    to [X1 X2 X2 X1] and [Y1 Y1 Y2 Y2]; therefore INDEX can range between
%    1 - 4 instead of 1 - 2.

% By:   S.C. Molitor (smolitor@med.unc.edu)
% Date: May 19, 2000

% default parameters

dist_err = 0.01;		% distance from vertex for selection (relative axes scale)
angle_tol = 0.01;		% segment angle tolerance (radians)

% initialize outputs

vert_index = [];
vert_flag = 0;
click_pt = [];

% check input parameters

if (nargin ~= 3)
   msgbox('Invalid number of arguments', 'ISVERTEX Error', 'warn');
   return
elseif (~istype(h_fig, 'figure'))
   msgbox('H_FIG must be a valid figure handle', 'ISVERTEX Error', 'warn');
   return
elseif (~istype(h_axes, 'axes'))
   msgbox('H_AXES must be a valid axes handle', 'ISVERTEX Error', 'warn');
   return
elseif (~istype(h_line, 'line') & ~istype(h_line, 'rectangle'))
   msgbox('H_LINE must be a valid line or rectangle handle', 'ISVERTEX Error', 'warn');
   return
end

% save last point clicked
% obtain rectangle/line vertices

get_point = get(h_axes, 'CurrentPoint');
click_pt = get_point(1, 1 : 2);
if (istype(h_line, 'rectangle'))
   rect_pos = get(h_line, 'Position');
   x_data = cumsum(rect_pos(1 : 2 : end));
   y_data = cumsum(rect_pos(2 : 2 : end));
   x_data = [x_data fliplr(x_data) x_data(1)];
   y_data = [y_data(1) y_data y_data(end) y_data(1)];
else
   x_data = get(h_line, 'XData');
   y_data = get(h_line, 'YData');
end

% determine distance between point & vertices
% find vert_index of closest vertex & whether closest vertex is within range

dist_sq = ((click_pt(1) - x_data)/diff(get(h_axes, 'XLim'))).^2 + ...
   ((click_pt(2) - y_data)/diff(get(h_axes, 'YLim'))).^2;
[min_dist_sq, min_index] = min(dist_sq);
if (min_dist_sq < dist_err.^2)
   vert_flag = 1;
   vert_index = min_index;
else
   vert_flag = 0;
   
   % take advantage of geometry to find segment
   % find angles between point & vertices
   % if point on a segment connecting vertices, diff(angles) = +/- 180!!
   
   pt_angle = atan2(click_pt(2) - y_data, click_pt(1) - x_data);
   [min_angle, vert_index] = min(abs(abs(diff(pt_angle)) - pi));
end
return
